package cn.liuhuan1.blogsModel.service;

import cn.liuhuan1.api.RedisClient;
import cn.liuhuan1.entity.ReturnResult;
import cn.liuhuan1.webModelBean.api.MailImp;
import cn.liuhuan1.webModelBean.vo.WebUserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.Date;
import java.util.List;
import java.util.Random;

/**
 * @Auther: liuhuan
 * @Date: 2021/4/21 - 04 - 21 - 21:08
 * @Description:
 * @version: 1.0
 */
@Service
public class MailService implements MailImp {

    @Autowired
    private RedisClient redisClient;
    private Random rand = new Random();
    @Autowired
    private JavaMailSenderImpl javaMailSender;
    @Autowired
    private WebUserService webUserService;
    private final static char[] letters=new char[]{'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q',
            'R','S','T','U','V','W','X','Y','Z','a','b','c','d','e','f','g','h','i',
            'j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','r',
            '0','1','2','3','4','5','6','7','8','9'};
    @Override
    public ReturnResult sendMail(@RequestParam("mail") String mail){

        ReturnResult returnResult = webUserService.getByMail(mail);
        if(returnResult.getCode().equals("500")){
            return returnResult;
        }
        if(returnResult.getData() != null){
            List<WebUserVo> webUserVoList = (List<WebUserVo>) returnResult.getData();
            if(webUserVoList != null || webUserVoList.size() > 0){
                return ReturnResult.error("500","邮箱已存在 请直接登录");
            }
        }
        String str = "";
        int index;
        boolean[] flags = new boolean[letters.length];//默认为false
        for(int i=0;i<5;i++){
            do{
                index = rand.nextInt(letters.length);
            }while(flags[index]==true);
            char c = letters[index];
            str += c;
            flags[index]=true;
        }
        redisClient.setValueDate(mail,str, (long) (60*5));
        // 构建一个邮件对象
        SimpleMailMessage message = new SimpleMailMessage();
        // 设置邮件主题
        message.setSubject("博客验证码：");
        // 设置邮件发送者，这个跟application.yml中设置的要一致
        message.setFrom("2806758770@qq.com");
        // 设置邮件接收者，可以有多个接收者，中间用逗号隔开，以下类似
        // message.setTo("10*****16@qq.com","12****32*qq.com");
        message.setTo(mail);
        // 设置邮件发送日期
        message.setSentDate(new Date());
        // 设置邮件的正文
        message.setText("博客验证码:"+ str);
        // 发送邮件
        javaMailSender.send(message);
        return ReturnResult.succes();
    }
}
